package com.lvyq.myplayer.common.util

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.core.content.FileProvider
import com.itheima.updatelib.PatchUtil
import com.lvyq.myplayer.model.version.UpVersionBean
import com.lvyq.myplayer.util.NetworkUtils
import com.lvyq.myplayer.util.ThreadUtil
import com.lvyq.myplayer.util.URLProviderUtils
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.toast
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import kotlin.time.Duration

/**
 * 文件描述：UpVersion
 * 作者：lvyq
 * 创建时间：2025-05-13
 * 修改时间：2025-05-13
 */
interface UpVersion {


    /**
     * 获取versionName
     */
    fun getAppVersionName(context: Context): String? {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 获取VersionCode
     */

    fun getAppVersionCode(context: Context): Long {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionCode.toLong()
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            -1 // 或者其他错误处理方式
        }
    }

    /**
     * 检测新版本通过code
     */
     fun checkVersion(versionCode: Long,context: Context,hand:Boolean) {
        val url = URLProviderUtils.checkVersion(versionCode)
        NetworkUtils.get(
            url = url,
            responseClass = UpVersionBean::class.java,
            successCallback = { versionInfo ->
                if (versionInfo.data!=null) {

                    CustomUpdateDialog(context)
                        .setTitle("发现新版本 ${versionInfo.data?.updVersion}")
                        .setContent(versionInfo.data?.content ?: "检测到新版本，立即更新以获得最佳体验")
                        .setOnConfirmListener {
                            /*if (hand){
                                apkDownAndInstall(versionInfo.data?.patchUrl?:"",context)
                            }else{
                                patchDown(versionInfo.data?.patchUrl?:"",context)
                            }*/
                          //  patchDown(versionInfo.data?.patchUrl?:"",context,versionInfo.data?.patchName?:"")
                            apkDownAndInstall(versionInfo.data?.patchUrl?:"",context)
                        }
                        .setOnCancelListener {
                            // 取消逻辑
                        }
                        .show()

                }else{
                    if (hand){
                         Toast.makeText(context, "已是最新版本", Toast.LENGTH_SHORT).show()                     }
                    }
            },
            errorCallback = { errorMsg ->
                Log.e("checkVersion", "加载失败：$errorMsg")
            }
        )
    }

    /**
     * 完整安装包下载
     */
     fun apkDownAndInstall(patchUrl:String,context: Context){
        //内部存储，应用卸载时随之删除
        var downloadDir= context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path ?: context.filesDir.path
        val newApkFile = File(downloadDir, "XSMusic_update.apk")
        // 如果文件不存在则下载
       // if (!newApkFile.exists()) {
            // 显示下载对话框
            /*mDialog.setMessage("正在下载更新包（${patchFile.name}）...")
            mDialog.show()*/
            var  mDialogP= ProgressDialog(context)
            mDialogP.setMessage("正在下载更新包（${newApkFile.name}）...")
            mDialogP.show()

            // 获取版本信息中的patch下载地址
            if (patchUrl.isNullOrEmpty()) {
                context.toast("更新地址不存在")
                return
            }

            // 异步下载任务
            doAsync {
                try {
                    val url = URL(patchUrl)
                    val connection = url.openConnection() as HttpURLConnection
                    connection.connect()

                    // 检查响应码
                    if (connection.responseCode != HttpURLConnection.HTTP_OK) {
                        throw IOException("服务器返回非200状态码: ${connection.responseCode}")
                    }

                    // 创建文件输出流
                    FileOutputStream(newApkFile).use { fos ->
                        val inputStream = connection.inputStream
                        val buffer = ByteArray(4096)
                        var bytesRead: Int

                        // 显示下载进度（需要实现进度回调）
                        val totalSize = connection.contentLength
                        var downloadedSize = 0L

                        while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                            fos.write(buffer, 0, bytesRead)
                            downloadedSize += bytesRead

                            // 更新UI进度（示例，需要实现进度回调）
                            val progress = (downloadedSize * 100 / totalSize.toFloat()).toInt()
                            context.runOnUiThread  {
                                mDialogP.setMessage("下载中... $progress%");
                            }
                        }
                    }

                    connection.disconnect()
                    // 下载完成后执行补丁操作

                    ThreadUtil.runOnMainThread() {
                        mDialogP.dismiss()
                        install(newApkFile,context)
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                    context.runOnUiThread  {
                        mDialogP.dismiss()
                        Toast.makeText(context, "下载失败: ${e.message ?: "未知错误"}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
    /* }else{
         install(newApkFile,context)
     }*/

}

    // 传统 Intent 方式（兼容旧版本）
    fun install(apkFile: File,context: Context) {
        try {
            val authority = "com.lvyq.myplayer.fileprovider"
            val apkUri = FileProvider.getUriForFile(context, authority, apkFile)

            // 创建安装 Intent
            val installIntent = Intent(Intent.ACTION_VIEW).apply {
                setDataAndType(apkUri, "application/vnd.android.package-archive")
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(installIntent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 差分包下载
     */
    fun patchDown(patchUrl:String,context: Context,patchName: String) {

        val pm: PackageManager = context.packageManager
        val appInfo = pm.getApplicationInfo(context.packageName, 0)
        val oldPath = appInfo.sourceDir

        var downloadDir= context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path ?: context.filesDir.path
        val newApkFile = File(downloadDir, "XSMusic_update.apk")
        //目前没有处理删除逻辑。本地patchName不可重复。
        val patchFile = File(downloadDir, patchName)

        // 如果patch文件不存在则下载
        if (!patchFile.exists()) {
            // 显示下载对话框
            var  mDialog= ProgressDialog(context)
            mDialog.setMessage("正在下载更新包（${patchFile.name}）...")
            mDialog.show()

            // 获取版本信息中的patch下载地址
            if (patchUrl.isNullOrEmpty()) {
                context.toast("未获取到更新包地址")
                mDialog.dismiss()
                return
            }

            // 异步下载任务
            doAsync {
                try {
                    val url = URL(patchUrl)
                    val connection = url.openConnection() as HttpURLConnection
                    connection.connect()

                    // 检查响应码
                    if (connection.responseCode != HttpURLConnection.HTTP_OK) {
                        throw IOException("服务器返回非200状态码: ${connection.responseCode}")
                    }

                    // 创建文件输出流
                    FileOutputStream(patchFile).use { fos ->
                        val inputStream = connection.inputStream
                        val buffer = ByteArray(4096)
                        var bytesRead: Int

                        // 显示下载进度（需要实现进度回调）
                        val totalSize = connection.contentLength
                        var downloadedSize = 0L

                        while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                            fos.write(buffer, 0, bytesRead)
                            downloadedSize += bytesRead

                            // 更新UI进度（示例，需要实现进度回调）
                            val progress = (downloadedSize * 100 / totalSize.toFloat()).toInt()
                            context.runOnUiThread {
                                mDialog.setMessage("下载中... $progress%")
                            }
                        }
                    }

                    connection.disconnect()

                    // 下载完成后执行补丁操作
                    context.runOnUiThread  {
                        mDialog.dismiss()
                        applyPatchAndInstall(oldPath, newApkFile, patchFile,context)
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                    context.runOnUiThread {
                        mDialog.dismiss()
                        toast("下载失败: ${e.message ?: "未知错误"}")
                    }
                }
            }
        } else {
            // 直接应用本地已有的patch
            applyPatchAndInstall(oldPath, newApkFile, patchFile, context )
        }
    }


    // 提取公共方法处理补丁应用和安装
    private fun applyPatchAndInstall(oldPath: String, newApkFile: File, patchFile: File,context: Context) {
        doAsync {
            try {
                // 应用补丁
                val result = PatchUtil.patch(oldPath, newApkFile.absolutePath, patchFile.absolutePath)
                if (result == 0) {
                    context.runOnUiThread {
                        install(newApkFile, context)
                    }
                } else {
                    context.runOnUiThread {
                        //mDialog.dismiss()
                        toast("补丁应用失败，错误码: $result")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                context.runOnUiThread {
                    //mDialog.dismiss()
                    toast("更新失败: ${e.message}")
                }
            }
        }
    }


}